import { ChangeDetectorRef } from '@angular/core';
import { StorageService } from '../../services/storage.service';
import * as _ from 'lodash';

export class BaseComponent {
    public productPermissions;
    private apiPrefix = 'api/v1';

    constructor(private cd: ChangeDetectorRef) {
        this.productPermissions = {
            'riskrating': this.hasPermission(`${this.apiPrefix}/riskratings/{companyId}`),
            'esg': this.hasPermission(`${this.apiPrefix}/esgratings/{companyId}`),
            'governance': this.hasPermission(`${this.apiPrefix}/governance`),
            'globalcompact': this.hasPermission(`${this.apiPrefix}/gcoverallcompanysummaryextended`),
            'controversies': this.hasPermission(`${this.apiPrefix}/company/{companyId}/esgControversyIndicator`),
            'sustainableproducts': this.hasPermission(`${this.apiPrefix}/sp`),
            'productinvolvement':  
                (this.hasPermission(`${this.apiPrefix}/companyassessments`, "GET", [{ key: "pi", value: "companyreport"}]) && this.hasPermission(`${this.apiPrefix}/pi`)) ||
                (this.hasPermission(`${this.apiPrefix}/companyassessmentshortreports`, "GET",  [{ key: "pi", value: "multicompanyreport"}]) && this.hasPermission(`${this.apiPrefix}/pi`))
        };
    }

    /**
     * Used especially for submenu company items to reset models to undefined and throw error so the global error handler manages it
     * @param callback The function to be executed to reset the component models
     * @param error The error to be thrown. If undefined, this is ignored
     */
    public errorCallback(callback: Function, error: any): void {
        callback();
        this.cd.markForCheck();
        if (error) {
            throw error;
        }
    }

    public hasPermission(resource: string, verb = 'GET', params: any = undefined): boolean {
        const permissions = StorageService.get().resourcePermissions;
        let filter = { resource: resource, verb: verb };
        if (params) filter['parameters'] = params;
        return _.filter(permissions, filter).length > 0;
    }
}
